package com.bluewap.telco;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.bluewap.core.AESGenerator;
import com.bluewap.core.Configuration;
import com.bluewap.core.Database;
import com.bluewap.core.StaticVar;
import com.bluewap.core.Util;

public class VivasEndServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private Logger log = Logger.getLogger("vivas");

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
	throws ServletException, IOException {
		String cpId = req.getParameter("cpId");
		String param = req.getParameter("param");
		String result = req.getParameter("result");
		String msisdn = req.getParameter("msisdn");
		String checker = req.getParameter("checker");

		log.debug(req.getQueryString());

		Configuration conf = Configuration.getInstance();
		String key = "";
		String verifyUrl = "";
		String contentid = "";
		String contentprice = "";
		String returnUrl = "";
		String token = "";

		try {
			Properties prop = conf.loadFile("vivas.properties");
			key = prop.getProperty("ENCRYPTKEY");
			verifyUrl = prop.getProperty("VERIFYURL");
			param = AESGenerator.decrypt(param.replace(" ", "+"), key);
			checker = AESGenerator.decrypt(checker.replace(" ", "+"), key);
			log.info(param);
		} catch (Exception e) {
			log.error("Error", e);
		}
		Map <String ,String> map = Util.getParam(param);
		String transId = map.get(StaticVar.TRANSID);

		Connection	conn = Database.getConnection();
		PreparedStatement st3 = null;
		PreparedStatement st4 = null;
		PreparedStatement st5 =null;
		ResultSet rs5 = null ;

		try {
			String query3 = "UPDATE OUTGOINGS SET STATUS = ? , MSISDN = ? WHERE ID = ?";
			String query4 = "UPDATE CHECKOUTS SET STATUS = ? , MSISDN = ? WHERE ID = ?";
			String query5 = "SELECT * FROM CHECKOUTS WHERE ID = ?" ;
			st3 = conn.prepareStatement(query3);
			st3.setInt(1, Integer.valueOf(result));
			st3.setString(2, msisdn);
			st3.setInt(3, Integer.valueOf(transId));
			st3.executeUpdate();
			st4 = conn.prepareStatement(query4);
			st4.setInt(1, Integer.valueOf(result));
			st4.setString(2, msisdn);
			st4.setInt(3, Integer.valueOf(transId));
			st4.executeUpdate();
			st5 = conn.prepareStatement(query5);
			st5.setInt(1, Integer.valueOf(transId));
			rs5 = st5.executeQuery();
			while(rs5.next()) {
				returnUrl = rs5.getString(StaticVar.DB_CHECKOUT_RETURNURL);
				contentid = rs5.getString(StaticVar.DB_CHECKOUT_CONTENTID);
				contentprice =rs5.getString(StaticVar.DB_CHECKOUT_CONTENTPRICE);
				token = rs5.getString(StaticVar.DB_CHECKOUT_TOKEN);
				break;
			}

		} catch (Exception e) {
			log.error("Error", e);
			Util.printJson(StaticVar.ERROR_INTERNAL_ERROR, null, resp);
			return;
		} finally {
			try {
				if (st3 != null)	st3.close();
				if (st4 != null)	st4.close();
				if (st5 != null)    st5.close();
				if (rs5 != null)    rs5.close();
				if (conn != null) Database.closeConnection(conn);
			} catch (Exception e) {
				log.error("Error", e);
			}
		}
		/*verify transaction*/
		if(result.equalsIgnoreCase("0")){
			if(contentprice.equals("0")){
				// wrong checker for detect
				if(!msisdn.equals(checker)){
					log.debug("Verify (checker) " + checker + " = (url) " + msisdn);
					result = String.valueOf(StaticVar.ERROR_CHARGE_FRAUD);
				}
			}
			else{
				// wrong result for charging
				try {
					param = "transactionId="+transId+"&contentId="+contentid+"&price="+contentprice + "&msisdn="+msisdn;
					param = AESGenerator.encrypt(param, key);
					List<String[]> parameters = new ArrayList<String[]>();
					String[] item = {"cpId", cpId};
					String[] item1 = {"param", param};
					parameters.add(item);
					parameters.add(item1);


					String resultTrans = Util.excuteProcessGET(parameters, verifyUrl);
					log.debug("Verify (api) " + resultTrans  + " = (url) " + result);
					if(!resultTrans.equalsIgnoreCase(result)) {
						result = String.valueOf(StaticVar.ERROR_CHARGE_FRAUD);
					}
				} catch (Exception e) {
					log.error("Error", e);
					Util.printJson(StaticVar.ERROR_INTERNAL_ERROR, null, resp);
				}
			}
		}
		returnUrl = Util.buildUrl(returnUrl, transId, token, msisdn, result);
		resp.sendRedirect(returnUrl);
	}

	public static void main(String[] args) {
		String tmp = AESGenerator.decrypt("lfKGuwj6FribBe1HJdU8Mg==", "1AHb6FH44e881eBB");
		System.out.println(tmp);
	}
}
